import { ref } from 'vue';
import { defineStore } from 'pinia';
import type { UserInfo } from '@/services/type';
import { api } from '@/services/api';
import { ElMessage } from 'element-plus';

export const useUserStore = defineStore('user', () => {

    // 用户信息
    const userInfo = ref<Partial<UserInfo>>({});

    // 获取登录用户信息
    const getInfo = async () => {
        // 调用获取登录用户信息接口
        const response = await api.user.getInfo();
        if(response.code === 0) {
            // 用户信息赋值
            userInfo.value = response.data;
            // 将用户信息保存到本地缓存
            localStorage.setItem("user", JSON.stringify(userInfo.value));
            // 返回用户信息
            return response.data;
        }
    }

    // 用户关注或取消关注
    const follow = async (yhnm?: string | null, is_follow?: boolean) => {
        // 调用用户关注或取消关注接口
        const response = await api.follow.follow({
            yhnm,
            is_follow
        });
        if(response.code === 0) {
            // 提示
            ElMessage.success(!is_follow ? "关注成功！" : "取消关注成功！");
        } else {`   `
            // 提示
            ElMessage.error(!is_follow ? "关注失败！" : "取消关注失败！");
        }
        return response;
    }

    return { userInfo, getInfo, follow };
});